package spring.my.db.sharding.demo.config.db;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import spring.my.db.sharding.demo.annotation.DataSourceAnnotation;

import java.lang.reflect.Method;

@Component
@Aspect
public class DataSourceAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "execution(public * spring.my.db.sharding.demo.service.impl.*.*(..))")
    public void dataSourceAnnotationPointCut() {
    }



    @Before("dataSourceAnnotationPointCut()")
    public void before(JoinPoint point) {
//        Object target = point.getTarget();
//        String method = point.getSignature().getName();
//
//        Class<?>[] clazz = target.getClass().getInterfaces();
//
//        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
//                .getMethod().getParameterTypes();
        try {
            Method m = ((MethodSignature) point.getSignature()).getMethod();
            if (m != null && m.isAnnotationPresent(DataSourceAnnotation.class)) {
                DataSourceAnnotation data = m.getAnnotation(DataSourceAnnotation.class);
                DynamicDataSourceHolder.putDataSource(data.value());
                // 当使用 slave 注解时改标志
                if (DynamicDataSourceHolder.DataSourceType.SLAVE.name().equalsIgnoreCase(data.value())) {
                    DynamicDataSourceHolder.isMaster = false;
                }
                log.info(">>>>  data type = {}", data.value());
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}
